import remoteSearchProductInput from '../../../order/components/remote-search-product-input';
import remoteSearchTechnologyOrderInput from '../../../order/components/remote-search-technology-order-input';
import {
	productionProcessPrdNoticeCreate,
	productionProcessPrdNoticeGet, productionProcessPrdNoticeUpdate, productionProcessPrdNoticeUpdateRelease,
	spinSpecSheetTaskBatchCreate
} from '../../../../../api/production/xsNotice';
import { formatDate, tipsBar } from '../../../../../utils/jk/jk-tool';
import { mathJsDiv } from '../../../../../utils/jk/jk-cals';
import checkboxPopover from '../../../order/components/form-box/checkbox-popover';
import { spinSpecSheetGet } from '../../../../../api/technology/order';
import { openStateList } from '../../../../../utils/jk/status-option-list';
import { productionPrdOrderGet } from '../../../../../api/production/order';
import { productionPrdNoticeMachineChangeCompleteRenovation, productionPrdNoticeMachineChangePage } from '../../../../../api/production/xsRenovateOrder';
import openCloseRenovate from '../../../productOpenCloseMachine/components/open-close-renovate';
import permissionMixin from '../../../../../mixins/permission-mixin';
import initFormData from './init-form-data';
import getTubeColor from '../../../foreSpinPrd/foreSpinningPlan/components/form-box/get-tube-color';
import machineStateBar from '../machine-state-bar';
import technologyNoticeBar from '../technology-notice-bar';
import remoteSearchOrderInput from '../remote-search-order-input';
import selectMachineGanttDialog from '../select-machine-gantt-dialog';
import noticeStateBar from '../notice-state-bar';
import noticeMachineList from '../notice-machine-list';
import handlerCache from '../../../../../mixins/handler-cache';
export default {
	components: {
		noticeMachineList,
		noticeStateBar,
		machineStateBar, technologyNoticeBar, remoteSearchOrderInput, checkboxPopover, selectMachineGanttDialog, remoteSearchProductInput, remoteSearchTechnologyOrderInput
	},
	mixins: [initFormData, openCloseRenovate, permissionMixin, getTubeColor, handlerCache],
	props: {
		pageType: {
			type: String,
			default: ''
		}
	},
	data() {
		return {
			apiItem: {
				'save': productionProcessPrdNoticeCreate,
				'update': productionProcessPrdNoticeUpdate
			},
			checkMachineData: [],
			showContentLoading: false,
			openStateList: openStateList,
			selectMachineGanttDialogState: false,
			dataId: null,
			saveBtnLoading: false,
			workshopList: [],
			processList: [],
			machineTaskList: [],
			saveDialogState: false,
			detailDataMachineList: [],
			dateVal: ''
		};
	},
	methods: {
		onDailyYieldChange(e) {
			this.ruleForm.prdNoticeMachineList.forEach(x => {
				if (!x.specSheet.code) {
					if (x.openingState !== 4) {
						x.specSheet.dailyYield = e;
						x.dailyYield = e;
					}
				}
			});
		},
		onAddMachineBtn() {
			// 除了已了机，不允许重复添加
			this.checkMachineData = this.ruleForm.prdNoticeMachineList ? this.ruleForm.prdNoticeMachineList.filter(x => x.openingState !== 4) : [];
			this.selectMachineGanttDialogState = true;
		},
		onNoticeBtn(id) {
			spinSpecSheetTaskBatchCreate([id]).then(res => {
				if (res.data.status === 200) {
					tipsBar(this, 'custom', 'success', '通知成功!');
					this.getDetailRequest();
				}
			});
		},
		onConfirmBtnOfSelectMachineGanttDialog(arr) {
			this.insertMachineData(arr);
			this.selectMachineGanttDialogState = false;
		},
		insertMachineData(arr) {
			const technologyInfo = JSON.parse(JSON.stringify(this.technologyOrderInfo));
			// 没有工艺单时，默认定量和台日单产
			if (!this.ruleForm.specSheetId) {
				technologyInfo.dailyYield = this.ruleForm.dailyYield;
				technologyInfo.meters = this.ruleForm.meters;
				technologyInfo.gramWeight = this.ruleForm.gramWeight;
			}
			// 机台的翻改日期、计划开台日期
			let changeD = '';
			if (formatDate(Date.now()) <= this.ruleForm.planStartDate) {
				changeD = this.ruleForm.planStartDate;
			} else {
				changeD = formatDate(Date.now());
			}
			arr.forEach(x => {
				technologyInfo.gramWeight = this.ruleForm.productOrder.gramWeight;
				technologyInfo.meters = this.ruleForm.productOrder.meters;
				this.ruleForm.prdNoticeMachineList.push({
					changeDate: changeD,
					time: '10:00:00',
					machineId: x.id,
					machineCode: x.code,
					machineName: x.name,
					machineModelId: x.machineModelId,
					machineModelCode: x.machineModelCode,
					machineModelName: x.machineModelName,
					ltMachineId: x.ltMachineId,
					ltMachineCode: x.ltMachineCode,
					ltMachineName: x.ltMachineName,
					productionQty: null,
					productionDays: null,
					subPlanStartDate: changeD,
					subPlanEndDate: '',
					dailyYield: this.ruleForm.dailyYield,
					processId: x.processId,
					processCode: x.processCode,
					processName: x.processName,
					specSheet: technologyInfo,
					openingState: 0,
					inputTubeColorList: this.ruleForm.inputTubeColorList ? JSON.parse(JSON.stringify(this.ruleForm.inputTubeColorList)) : [],
					outputTubeColorList: this.ruleForm.outputTubeColorList ? JSON.parse(JSON.stringify(this.ruleForm.outputTubeColorList)) : [],
					paperTubeList: this.ruleForm.paperTubeList ? JSON.parse(JSON.stringify(this.ruleForm.paperTubeList)) : []
				});
			});
		},
		onRemoveBtn(scope) {
			this.ruleForm.prdNoticeMachineList.splice(scope.rowIndex, 1);
		},
		getOrderDetailRequest() {
			if (this.ruleForm.orderIssued.order.id) {
				return productionPrdOrderGet({ id: this.ruleForm.orderIssued.order.id }).then(res => {
					if (res.data.status === 200) {
						const arr = res.data.res.coarseSandList ? res.data.res.coarseSandList.map(x => {
							delete x.id;
							return x;
						}) : [];
						this.$set(this.ruleForm, 'spunYarnBomItemList', arr);
					}
				});
			}
		},
		onSelectTechnologyOrderChange(e) {
			this.clearFormItemVal('technology');
			if (e && Object.keys(e).length) {
				this.$set(this.ruleForm, 'specSheetId', e.id);
				this.$set(this.ruleForm, 'specSheetCode', e.code);
				this.$set(this.ruleForm, 'machineModelId', e.machineModelId);
				this.$set(this.ruleForm, 'machineModelCode', e.machineModelCode);
				this.$set(this.ruleForm, 'machineModelName', e.machineModelName);
				this.$set(this.ruleForm, 'dailyYield', e.dailyYield);
				this.$set(this.ruleForm, 'moistureRegain', e.moistureRegain);
				this.$set(this.ruleForm, 'efficiencyPercent', e.efficiencyPercent);
				this.$set(this.ruleForm, 'gramWeight', e.gramWeight);
				this.$set(this.ruleForm, 'meters', e.meters);
				this.ruleForm.prdNoticeMachineList.forEach(x => {
					this.$set(x, 'dailyYield', e.dailyYield);
					this.$set(x, 'gramWeight', e.gramWeight);
					this.$set(x, 'meters', e.meters);
					this.$set(x, 'specSheetId', e.id);
					this.$set(x, 'specSheetCode', e.code);
					this.$set(x, 'specSheet', {}); // specSheetId和specSheet是二选一的关系,specSheet是针对没有工艺单时直接录入工艺项目
					if (x.productionQty && x.dailyYield && x.subPlanStartDate) {
						const days = Math.ceil(mathJsDiv(x.productionQty, e.dailyYield));
						this.$set(x, 'productionDays', days);
						this.$set(x, 'subPlanEndDate', formatDate(Date.parse(x.subPlanStartDate) + (days * 24 * 60 * 60 * 1000)));
					}
				});
				this.getTechnologyOrderDetailRequest(e.id);
			} else {
				this.$set(this.ruleForm, 'specSheetId', null);
				this.$set(this.ruleForm, 'specSheetCode', '');
				this.$set(this.ruleForm, 'machineModelId', null);
				this.$set(this.ruleForm, 'machineModelCode', '');
				this.$set(this.ruleForm, 'machineModelName', '');
				this.$set(this.ruleForm, 'dailyYield', null);
				this.$set(this.ruleForm, 'moistureRegain', null);
				this.$set(this.ruleForm, 'efficiencyPercent', null);
				this.$set(this.ruleForm, 'meters', null);
				this.$set(this.ruleForm, 'gramWeight', null);
			}
		},
		getTechnologyOrderDetailRequest(id) {
			return spinSpecSheetGet({ id }).then(res => {
				if (res.data.status === 200) {
					this.technologyOrderInfo = res.data.res;
					this.technologyOrderInfo.specSheetParamList.map(x => {
						x.val = x.dataType === 1 ? Number(x.val) : x.val;
						x.valMax = x.dataType === 1 ? Number(x.valMax) : x.valMax;
						x.valMin = x.dataType === 1 ? Number(x.valMin) : x.valMin;
						return x;
					});
				}
			});
		},
		onVisibleChangeOfSelectMachineGanttDialog(e) {
			this.selectMachineGanttDialogState = e;
		},
		onPrintBtn() {
			const routeUrl = this.$router.resolve({
				name: 'printOrder',
				query: {
					id: this.ruleForm.productOrderId
				}
			});
			window.open(routeUrl.href, '_blank');
		},
		onPrintMachineBtn() {
			const routeUrl = this.$router.resolve({
				name: 'printMachine',
				query: {
					id: this.ruleForm.id
				}
			});
			window.open(routeUrl.href, '_blank');
		},
		onJumpOrder() {
			this.$store.dispatch('tagsView/delView', { path: this.$route.path });
			this.$toOtherRouter({
				name: 'editPrdOrder',
				query: {
					id: this.ruleForm.productOrder.id
				}
			});
		},
		onJumpList() {
			this.$store.dispatch('tagsView/delView', { path: this.$route.path });
			this.$toMainRouter({
				name: 'ProductionNoticeOrder'
			});
		},
		onJump(id) {
			this.$store.dispatch('tagsView/delView', { path: this.$route.path });
			this.$toOtherRouter({
				name: 'editProductionNoticeOrder',
				query: {
					id: id
				}
			});
		},
		onSelectEmpChange(e) {
			if (Object.keys(e).length) {
				this.$set(this.ruleForm, 'plannerId', e.id);
				this.$set(this.ruleForm, 'plannerName', e.name);
			}
		},
		onSelectCustomerChange(e) {
			if (Object.keys(e).length) {
				this.$set(this.ruleForm, 'customerId', e.id);
				this.$set(this.ruleForm, 'customerName', e.name);
			}
		},
		onSelectBatchCodeChange(e) {
			if (Object.keys(e).length) {
				this.$set(this.ruleForm, 'batchCode', e.batchCode);
			}
		},
		getParamData() {
			const params = JSON.parse(JSON.stringify(this.ruleForm));
			params.prdNoticeMachineList = this.ruleForm.prdNoticeMachineList.map(x => x);
			params.machineQty = params.prdNoticeMachineList.length;
			if (params.workshopId) params.workshopName = this.workshopList.find(x => x.id === params.workshopId).name;
			delete params.productOrderBatchItem;
			return params;
		},
		onConfirmBtn(type) {
			this.$refs['ruleForm'].validate(valid => {
				if (valid) {
					if (this.ruleForm.prdNoticeMachineList && this.ruleForm.prdNoticeMachineList.length) {
						this.createAndUpdateRequest(type);
					} else {
						this.$tipsBar(this, 'custom', 'warning', '机台不能为空!');
					}
				} else {
					this.$tipsBar(this, 'custom', 'warning', '细纱管、纸管颜色或其他必填项未填写完整!');
				}
			});
		},
		createAndUpdateRequest(type) {
			this.saveBtnLoading = true;
			// 新增
			if (!this.dataId) {
				this.ruleForm.id = null;
				productionProcessPrdNoticeCreate(this.getParamData()).then(res => {
					this.saveBtnLoading = false;
					if (res.data.status === 200) {
						this.$tipsBar(this, 'save');
						this.onJump(res.data.res);
					}
				});
				return;
			}
			const api = type === 1 ? productionProcessPrdNoticeUpdateRelease : productionProcessPrdNoticeUpdate;
			// 编辑
			api(this.getParamData()).then(res => {
				this.saveBtnLoading = false;
				if (res.data.status === 200) {
					this.$tipsBar(this, 'save');
					this.getDependentData();
				}
			});
		},
		onVisibleChange(e) {
			this.$emit('on-visible-change', e);
			if (!e) {
				Object.assign(this.$data, this.$options.data());
				this.$nextTick(() => {
					this.$refs.ruleForm.resetFields();
				});
			}
		},
		showLoading(e) {
			this.showContentLoading = e;
		},
		getDetailRequest() {
			return productionProcessPrdNoticeGet({ id: this.$route.query.id }).then(res => {
				if (res.data.status === 200) {
					const resData = res.data.res ? JSON.parse(JSON.stringify(res.data.res)) : {};
					resData.prdNoticeMachineList.forEach(k => {
						if (k.specSheet && k.specSheet.specSheetParamList) {
							k.specSheet.specSheetParamList.forEach(x => {
								// 做类型转换，避免组件报错
								x.val = x.dataType === 1 ? Number(x.val) : x.val;
								x.valMax = x.dataType === 1 ? Number(x.valMax) : x.valMax;
								x.valMin = x.dataType === 1 ? Number(x.valMin) : x.valMin;
							});
						}
					});
					resData.machineParams = resData.machineParams || {};
					resData.orderIssued = resData.orderIssued || { order: {}};
					resData.paperTubeList = resData.paperTubeList || [];
					this.ruleForm = resData;
					this.detailDataMachineList = res.data.res ? res.data.res.prdNoticeMachineList : [];
					if (this.ruleForm.specSheetId) {
						this.getTechnologyOrderDetailRequest(this.ruleForm.specSheetId);
					}
					// 通过后纺排产中心选择机台时，将机台放入对应的工序内
					if (this.$route.query.machineList) {
						let machineData = JSON.parse(this.$route.query.machineList).map(x => {
							return {
								id: x.machineId,
								code: x.machineCode,
								name: x.machineName,
								processId: x.processId,
								processCode: x.processCode,
								processName: x.processName
							};
						});
						// 过滤已有的且未了机的机台
						machineData.forEach(newMachineItem => {
							newMachineItem.isExit = false;
							this.ruleForm.prdNoticeMachineList.forEach(exitMachineItem => {
								// 未了机的
								if (newMachineItem.id === exitMachineItem.machineId && exitMachineItem.openingState < 4) {
									newMachineItem.isExit = true;
								}
							});
						});
						machineData = machineData.filter(x => !x.isExit);
						this.insertMachineData(machineData);
					}

					this.$emit('return', res.data.res);
				}
			});
		},
		getMachineTaskListRequest() {
			if (this.ruleForm.code && this.ruleForm.id) {
				return productionPrdNoticeMachineChangePage({
					prdNoticeCode: this.ruleForm.code
				}).then(res => {
					if (res.data.status === 200) {
						this.machineTaskList = res.data.res;
					}
				});
			} else {
				return new Promise((resolve, reject) => resolve());
			}
		},
		finishRenovate(id) {
			this.$confirm(`确定"完成翻改"吗？`, '提示', { type: 'warning' }).then(() => {
				productionPrdNoticeMachineChangeCompleteRenovation({ id: id }).then(res => {
					if (res.data.status === 200) {
						this.getListRequest();
					}
				});
			}).catch(() => {});
		},
		getListRequest() {
			this.getDependentData();
		},
		onToggleColorChange(data, key) {
			this.ruleForm.prdNoticeMachineList.forEach(x => {
				if (x.openingState !== 4) {
					this.$set(x, key, data);
				}
			});
		},
		onGramWeightChange(data, key) {
			this.ruleForm.prdNoticeMachineList.forEach(x => {
				if (x.openingState !== 4) {
					this.$set(x, key, data);
					this.$set(x.specSheet, key, data);
				}
			});
		},
		async getDependentData() {
			this.showLoading(true);
			this.dataId = this.$route.query.id ? Number(this.$route.query.id) : null;
			if (this.pageType !== 'detail') {
				this.workshopList = this.$store.state.user.userWorkshop.workshopList;
				if (!this.dataId) {
					this.$set(this.ruleForm, 'workshopId', this.$store.state.user.userWorkshop.defaultWorkshopId);
					this.$set(this.ruleForm, 'workshopCode', this.$store.state.user.userWorkshop.defaultWorkshopCode);
					this.$set(this.ruleForm, 'workshopName', this.$store.state.user.userWorkshop.defaultWorkshopName);
					this.$set(this.ruleForm, 'belongDate', formatDate(Date.now()));
				}
			}
			await this.getLtColorListRequest();
			if (this.dataId) await this.getDetailRequest();
			if (this.getColorInfoByProcess(this.ruleForm.processCode)) await this.getInputColorListRequest(this.getColorInfoByProcess(this.ruleForm.processCode).inputTypeCode);
			if (this.getColorInfoByProcess(this.ruleForm.processCode)) await this.getOutColorListRequest(this.getColorInfoByProcess(this.ruleForm.processCode).outTypeCode);
			await this.getMachineTaskListRequest();
			this.$nextTick(() => {
				this.$refs.ruleForm.clearValidate();
			});
			this.showLoading(false);
		},
		clearCacheMethod() {
			Object.assign(this.$data, this.$options.data());
			this.$nextTick(() => {
				this.$refs.ruleForm.clearValidate();
				this.getDependentData();
			});
		}
	}
};
